//
//  GDFRequestManager.m
//
//
//  Created by lanou on 15/12/22.
//  Copyright (c) 2015年 zj. All rights reserved.
//

#import "GDFRequestManager.h"

@implementation GDFRequestManager
+ (void)requestWithUrl:(NSString *)urlstring
               parmDic:(NSDictionary *)parmDic
                method:(RequsetType)method
       succeedWithData:(void(^)(NSData *data))block
       failedWithError:(void(^)(NSError *connectionError))error{
    // 处理中文字符串
    NSString *string = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlstring];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // post 请求方式的处理
    if (method == POST1 ){
        [request setHTTPMethod:@"POST"];
        // 字典的参数不为空 需要把内容拼接起来
        if (parmDic.count != 0){
            NSMutableArray *strArray = [NSMutableArray array];
            for (NSString *key in parmDic) {
                NSString *str = [NSString stringWithFormat:@"%@=%@",key,parmDic[key]];
                [strArray addObject:str];
            }
            // 使用数组的方法 拼接数组内的元素
            NSString *parm = [strArray componentsJoinedByString:@"&"];
            [request setHTTPBody:[parm dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        // 缓存设置
        NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *savePath = [docPath stringByAppendingPathComponent:@"savePath"];
        
        if (connectionError == nil){
            // 存入本地
            NSString *path = [NSString stringWithFormat:@"%@/#%ld.cgtu",docPath,(unsigned long)data.hash];
            [NSKeyedArchiver archiveRootObject:data toFile:path];
            [NSKeyedArchiver archiveRootObject:path toFile:savePath];
<<<<<<< HEAD
            //NSLog(@" ********************  %@",data);
=======
>>>>>>> 3cb8f4b1a0e492cb51ded6afbb48d6c71a113a13
            block(data);
            
        }else{
            error(connectionError);
            // 读取本地的上一次缓存文件
            NSString *s = [NSKeyedUnarchiver unarchiveObjectWithFile:savePath];
            NSString *str = [[s componentsSeparatedByString:@"#"] lastObject];
            NSString *path = [NSString stringWithFormat:@"%@/#%@",docPath,str];
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if (pickData != nil && ![pickData isKindOfClass:[NSNull class]]){
                block(pickData);
            }
        }
    }];

}
@end
